package com.xhwl.data.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.xhwl.common.dto.cent.sdata.*;
import com.xhwl.common.enums.AppTypeEnum;
import com.xhwl.common.enums.BusinessRangeTypeEnum;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.enums.config.BusinessType;
import com.xhwl.common.enums.config.IndustryEnum;
import com.xhwl.common.enums.config.InitializeEnum;
import com.xhwl.common.enums.config.RoleTypeEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.*;
import com.xhwl.common.pojo.cent.sdata.devplatform.Developer;
import com.xhwl.common.query.cent.AdminAccountQuery;
import com.xhwl.common.query.cent.sdata.*;
import com.xhwl.common.utils.PageUtil;
import com.xhwl.data.dao.ISceneRoleDao;
import com.xhwl.data.pojo.RoleTypeQuery;
import com.xhwl.data.pojo.vo.RoleQueryVO;
import com.xhwl.data.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * @Author: JCccc
 * @Description:
 * @Date: Create in 16:02 2021/1/12
 */
@RestController
public class RoleController {
    private static final Logger log = LoggerFactory.getLogger(RoleController.class);
    @Autowired
    IRoleService roleService;
    @Autowired
    ISceneRoleDao sceneRoleDao;
    @Autowired
    IAccountService accountService;
    @Autowired
    IEnterpriseService enterpriseService;
    @Autowired
    IProjectService projectService;
    @Autowired
    IOrganizationService organizationService;
    @Autowired
    IAccountRoleService accountRoleService;
    @Autowired
    IAdminAccountRoleService adminAccountRoleService;
    @Autowired
    IRolePermissionService rolePermissionService;
    @Autowired
    IPermissionService permissionService;
    @Autowired
    private IIndustryService industryService;

    @Autowired
    private IAdminAccountService adminAccountService;
    /**
     * 角色类型身份选择器
     *
     * @return
     */
    @GetMapping(value = "/role/get-role-type")
    public ResultJson getRoleTyp() {
        return roleService.getRoleType();
    }

    @PostMapping("/role/get-type/v2")
    public ResultJson getRoleTypeV2(@RequestBody RoleTypeQuery roleTypeQuery){
        List<Map<String, Object>> result = roleService.getRoleType(roleTypeQuery);
        return ResultJson.success(result);
    }


    /**
     * 角色新增
     *
     * @param appId
     * @param clientType
     * @param industryId
     * @param roleGrantDTO
     * @param operateAccount
     * @return
     */
    @RequestMapping(value = "/role/add", method = RequestMethod.POST)
    public ResultJson roleAdd(@RequestHeader(value = "appId", required = true) String appId,
                              @RequestHeader(value = "clientType", required = false) Integer clientType,
                              @RequestHeader(value = "industryId") Short industryId,
                              @RequestBody RoleGrantDTO roleGrantDTO,
                              Account operateAccount, AdminAccount adminAccount, App app) {
        ResultJson resultJson;
        if(null == roleGrantDTO.getIndustryId()){
            roleGrantDTO.setIndustryId(industryId);
        }
        roleGrantDTO.setAppId(appId);

        if(AppTypeEnum.SYSTEM.type == app.getAppType().intValue()){
            roleGrantDTO.setOperateAccountId(adminAccount.getId());
            roleGrantDTO.setOperateAccountLoginName(adminAccount.getLoginName());
            roleGrantDTO.setOperateAccountName(adminAccount.getName());
        }else{
            roleGrantDTO.setOperateAccountId(operateAccount.getId());
            roleGrantDTO.setOperateAccountLoginName(operateAccount.getLoginName());
            roleGrantDTO.setOperateAccountName(operateAccount.getName());
        }
        if (null == roleGrantDTO.getId()) {
//            if (RoleTypeEnum.COMMON.getCode() != roleGrantDTO.getType()) {
//                return ResultJson.fail("不可新增除普通类型角色外的角色");
//            }
            resultJson = roleService.createRole(roleGrantDTO);
        } else {
            resultJson = roleService.updateRole(operateAccount, roleGrantDTO);
        }
        return resultJson;
    }

    /**
     * 运管平台添加角色
     * @param appId
     * @param roleGrantDTO
     * @param adminAccount
     * @return
     */
    @RequestMapping(value = "/role/admin-add", method = RequestMethod.POST)
    public ResultJson roleAdminAdd(@RequestHeader(value = "appId", required = false) String appId,
                                   @RequestHeader(value = "industryId", required = false) Short industryId,
                                   @RequestBody RoleGrantDTO roleGrantDTO, AdminAccount adminAccount){
        if(null == roleGrantDTO.getIndustryId()){
            roleGrantDTO.setIndustryId(industryId);
        }
        if(null != roleGrantDTO.getGrade() && roleGrantDTO.getGrade() != 2){
            // 非业态角色没有业态id
            roleGrantDTO.setIndustryId(null);
        }
        if(null == roleGrantDTO.getGrade()){
            return ResultJson.fail("缺少角色等级");
        }
        if(null == roleGrantDTO.getId()){
            return roleService.createRoleAdminV2(roleGrantDTO, adminAccount);
        }else{
            return roleService.updateRoleAdminV2(roleGrantDTO, adminAccount);
        }
    }

    /**
     * 角色名验重
     *
     * @param appId
     * @param clientType
     * @param industryId
     * @param organizationId
     * @param name
     * @param operateAccount
     * @return
     */
    @RequestMapping(value = "/role/name-exist-check", method = RequestMethod.GET)
    public ResultJson roleNameExistChecking(@RequestHeader(value = "appId", required = true) String appId,
                                            @RequestHeader(value = "clientType", required = false) Integer clientType,
                                            @RequestHeader(value = "industryId", required = true) Short industryId,
                                            @RequestParam("organizationId") Integer organizationId,
                                            @RequestParam(value = "id", required = false) Integer id,
                                            @RequestParam("name") String name,
                                            Account operateAccount) {
        RoleGrantDTO roleGrantDTO = new RoleGrantDTO();
        roleGrantDTO.setIndustryId(industryId);
        roleGrantDTO.setAppId(appId);
        roleGrantDTO.setName(name);
        roleGrantDTO.setId(id);
        roleGrantDTO.setOrganizationId(organizationId);
        return roleService.roleNameExistCheck(roleGrantDTO);
    }


    /**
     * 角色修改
     *
     * @param appId
     * @param clientType
     * @param industryId
     * @param roleGrantDTO
     * @param operateAccount
     * @return
     */
    @RequestMapping(value = "/role/update", method = RequestMethod.POST)
    public ResultJson roleUpdate(@RequestHeader(value = "appId", required = true) String appId,
                                 @RequestHeader(value = "clientType", required = false) Integer clientType,
                                 @RequestHeader(value = "industryId", required = true) Short industryId,
                                 @RequestBody RoleGrantDTO roleGrantDTO,
                                 Account operateAccount) {
        roleGrantDTO.setIndustryId(industryId);
        roleGrantDTO.setAppId(appId);
        return roleService.updateRole(operateAccount, roleGrantDTO);
    }

    /**
     * 角色删除
     *
     * @param appId
     * @param clientType
     * @param industryId
     * @param id
     * @param operateAccount
     * @return
     */
    @RequestMapping(value = "/role/delete", method = RequestMethod.GET)
    public ResultJson roleDelete(@RequestHeader(value = "appId", required = true) String appId,
                                 @RequestHeader(value = "clientType", required = false) Integer clientType,
                                 @RequestHeader(value = "industryId", required = true) Short industryId,
                                 @RequestParam(value = "id") Integer id,
                                 Account operateAccount) {
        log.info("删除角色参数id={}", id);
        //若角色还存在账号关联，不允许删除
        List<Integer> accountIdListByRoleId = accountService.getAccountIdListByRoleId(id);
        if (!accountIdListByRoleId.isEmpty()) {
            return ResultJson.fail("角色还有账号使用，不能删除");
        }
        AdminAccountQuery adminAccountQuery = new AdminAccountQuery();
        adminAccountQuery.setRoleId(id);
        if(!CollectionUtils.isEmpty(adminAccountService.getList(adminAccountQuery))){
            return ResultJson.fail("角色还有账号使用，不能删除");
        }
        //若角色id不存在，无感知删除返回成功
        Role role = roleService.getRoleById(id);
        if (Objects.isNull(role)) {
            return ResultJson.success(id);
        }
        //若角色为内置级别，不允许删除
//        int isInitialized = role.getIsInitialized() ? 1 : 0;
//        if (InitializeEnum.IS_INITIALIZE.code == isInitialized) {
//            return ResultJson.fail("内置角色，不能删除");
//        }
        roleService.deleteRole(operateAccount, id);
        return ResultJson.success();
    }

    @PostMapping("/role/list-name")
    public ResultJson list(@RequestBody RoleQuery roleQuery) {
        if (roleQuery.getEnterpriseIdList().isEmpty()){
            return ResultJson.fail("缺少企业信息");
        }
        List<Role> roles1 = roleService.getList(roleQuery);
        return ResultJson.success(roles1);
    }




    @GetMapping("/role/getRolesByRoleIds")
    public ResultJson getRoles(@RequestParam( "roleIds" )   List<Integer> roleIds) {
        if (roleIds.isEmpty()){
            return ResultJson.success(null);
        }
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.in("id",roleIds);
        List<Role> list = roleService.list(roleQueryWrapper);
        return ResultJson.success(list);
    }


    @GetMapping("/role/check-roles")
    public ResultJson checkRole(@RequestParam( "roleIds" )  List<Integer> roleIds) {
        if (roleIds.isEmpty()){
            return ResultJson.success(null);
        }
        List<RoleDetailDTO> roleDetailDTOS = accountRoleService.getCountByRoleId(roleIds);
        int count = 0;
        for (RoleDetailDTO roleDetailDTO : roleDetailDTOS){
            if (0 != roleDetailDTO.getCount()){
                count ++ ;
            }
        }
        return ResultJson.success(count>0);
    }

    /**
     * 角色信息查询
     *
     * @param page
     * @param organizationIds
     * @param name
     * @param operateAccount
     * @return
     */
    @RequestMapping(value = "/role/list", method = RequestMethod.GET)
    public ResultJson roleList(Page page,
                               @RequestHeader(value = "industryId", required = true) Short industryId,
                               @RequestParam(value = "organizationIds", required = false) List<Integer> organizationIds,
                               @RequestParam(value = "proIds", required = false) List<Integer> proIds,
                               @RequestParam(value = "name", required = false) String name,
                               @RequestParam(value = "needAuth", required = false) Boolean needAuth,
                               @RequestParam(value = "permissionCodes", required = false) List<String> permissionCodes,
                               @RequestParam(value = "needCommonInitialized", required = false) Boolean needCommonInitialized,
                               @RequestParam(value = "needSuperAdmin", required = false) Boolean needSuperAdmin,
                               @RequestParam(value = "orderAsc", required = false,defaultValue = "true") Boolean orderAsc,
                               Account operateAccount) {
        if (Objects.isNull(needAuth)) {
            needAuth = true;
        }
        if (Objects.isNull(needSuperAdmin)) {
            needSuperAdmin = true;
        }
        Page<Role> roleResultList = new Page<>();
        //获取当前登录操作账号的角色身份
        RoleTypeDTO accountRoleType = roleService.getAccountRoleType(operateAccount.getId());
        RoleTypeEnum operateRoleType = accountRoleType.getRoleTypeEnum();
        RoleQuery roleQuery = new RoleQuery();
        if (!CollectionUtils.isEmpty(organizationIds)) {
            roleQuery = covertOrProIdEntIds(organizationIds);
        }
        if (!CollectionUtils.isEmpty(permissionCodes)) {
            roleQuery.setPermissionCodes(permissionCodes);
        }
        roleQuery.setNeedSuperAdmin(needSuperAdmin);
        // 2022-10-16 取消角色与平台关系
        //roleQuery.setIndustryIdList(Arrays.asList(industryId));
        // 2022-10-19 取消默认非内置查询，由传参决定
        if (Objects.nonNull(needCommonInitialized)) {
            roleQuery.setNeedCommonInitialized(needCommonInitialized);
        }
        if (StringUtils.isNotEmpty(name)) {
            roleQuery.setLikeName(name);
        }
        if (!CollectionUtils.isEmpty(proIds)) {
            if (!CollectionUtils.isEmpty(roleQuery.getOrProjectIdList())) {
                List<Integer> orProjectIdList = roleQuery.getOrProjectIdList();
                List<Integer> crossProjectIds = proIds.stream().filter(orProjectIdList::contains).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(crossProjectIds)) {
                    return ResultJson.success(roleResultList);
                }
                roleQuery.setOrProjectIdList(crossProjectIds);
            } else {
                roleQuery.setOrProjectIdList(proIds);
            }
        }
        //设置默认排序为升序
        roleQuery.setOrderColumn("id");
        roleQuery.setOrderAsc(orderAsc);
        if (needAuth) {
//            if (RoleTypeEnum.PRO_MANAGER.getCode() == operateRoleType.getCode()) {
//                //如果是项目管理员，需要对项目取交集
//                List<Integer> projectIdList = accountRoleType.getProjectIdList();
//                roleQuery.setProjectIdList(projectIdList);
//            }
            if (RoleTypeEnum.ENT_MANAGER.getCode() == operateRoleType.getCode() || RoleTypeEnum.PRO_MANAGER.getCode() == operateRoleType.getCode() || RoleTypeEnum.COMMON.getCode() == operateRoleType.getCode()) {
                //如果是企业管理员，需要对企业取交集
                List<Integer> enterpriseIdList = accountRoleType.getEnterpriseIdList();
                roleQuery.setEnterpriseIdList(enterpriseIdList);
            }
            roleResultList = roleService.getRolePageList(operateAccount, page, roleQuery);
        } else {
            roleResultList = roleService.getRolePageList(null, page, roleQuery);
        }
        List<Role> roleList = roleResultList.getRecords();
        if (CollectionUtils.isEmpty(roleList)) {
            return ResultJson.success(roleResultList);
        }
        //获取角色需要填充的组织架构数据
        RoleOrgStructureDTO roleOrgStructureData = roleService.getRoleOrgStructureData(roleList);
        //填充信息
        List<RoleDetailDTO> resultList = fillRoleDetailList(roleList, roleOrgStructureData, operateRoleType);
        //动态查询角色详情 分页数据组装
        Page<RoleDetailDTO> resultPageList = new Page<>();
        //根据最后的查询结果进行分页重组
        resultPageList.setTotal(roleResultList.getTotal());
        resultPageList.setSize(roleResultList.getSize());
        resultPageList.setCurrent(roleResultList.getCurrent());
        resultPageList.setRecords(resultList);
        return ResultJson.success(resultPageList);
    }

    /**
     * 分页查询 兼容前后台
     * @param roleQueryVO
     * @return
     */
    @PostMapping("/role/page")
    public ResultJson page(@RequestBody RoleQueryVO roleQueryVO, App app, Developer developer){
        roleQueryVO.getRoleQuery().setDevelopId(developer.getId());
        Page roles = roleService.getRolePageList(null, roleQueryVO.getPage(), roleQueryVO.getRoleQuery());
        List<Role> roles1 = roles.getRecords();
        Map<Integer, Long> roleCountMap = new HashMap<>();
        Map<Integer, List<Integer>> rolePermissionMap = new HashMap<>();
        Map<Integer, String> permissionMap = new HashMap<>();
        Map<Integer, String> enterpriseMap = new HashMap<>();
        Map<Integer, String> industryMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(roles1)){
            List<Integer> roleIds = new ArrayList<>();
            List<Integer> enterpriseId = new ArrayList<>();
            List<Integer> industryIds = new ArrayList<>();
            for (Role role : roles1) {
                roleIds.add(role.getId());
                if(null != role.getEnterpriseId()){
                    enterpriseId.add(role.getEnterpriseId());
                }
                if(null != role.getIndustryId()){
                    industryIds.add(role.getIndustryId().intValue());
                }
            }
            // 角色人数统计
            roleCountMap = roleAccountCount(roleIds);

            QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
            rolePermissionQueryWrapper.in("role_id", roleIds);
            List<RolePermission> list = rolePermissionService.list(rolePermissionQueryWrapper);
            if(!list.isEmpty()){
                List<Integer> permissionIds = list.stream().map(i -> i.getPermissionId()).distinct().collect(Collectors.toList());
                rolePermissionMap = list.stream().collect(Collectors.groupingBy(RolePermission::getRoleId, Collectors.mapping(RolePermission::getPermissionId, Collectors.toList())));
                List<Permission> permissions = permissionService.listByIds(permissionIds);
                if(!permissions.isEmpty()){
                    permissionMap = permissions.stream().collect(Collectors.toMap(Permission::getId, Permission::getName));
                }
            }
            // 企业名称回显
            if(!CollectionUtils.isEmpty(enterpriseId)){
                QueryWrapper<Enterprise> enterpriseQueryWrapper = new QueryWrapper<>();
                enterpriseQueryWrapper.select("id", "name");
                enterpriseQueryWrapper.in("id", enterpriseId.stream().distinct().collect(Collectors.toList()));
                List<Enterprise> list1 = enterpriseService.list(enterpriseQueryWrapper);
                if(!CollectionUtils.isEmpty(list1)){
                    enterpriseMap = list1.stream().collect(Collectors.toMap(Enterprise::getId, Enterprise::getName));
                }
            }
            // 平台名称回显
            if(!CollectionUtils.isEmpty(industryIds)){
                QueryWrapper<Industry> industryQueryWrapper = new QueryWrapper<>();
                industryQueryWrapper.select("id", "name");
                industryQueryWrapper.in("id", industryIds.stream().distinct().collect(Collectors.toList()));
                List<Industry> list1 = industryService.list(industryQueryWrapper);
                if(!CollectionUtils.isEmpty(list1)){
                    industryMap = list1.stream().collect(Collectors.toMap(Industry::getId, Industry::getName));
                }
            }

        }
        List<RoleDetailDTO> roleDetailDTOS = new ArrayList<>(roles1.size());
        for (Role role : roles1) {
            RoleDetailDTO roleDetailDTO = new RoleDetailDTO();
            BeanUtils.copyProperties(role, roleDetailDTO);
            roleDetailDTO.setIsInitializedName(role.getIsInitialized() ? "内置角色": "自定义角色");
            roleDetailDTO.setCount(roleCountMap.get(role.getId()) == null ? 0: roleCountMap.get(role.getId()).intValue());
            List<Integer> permissionIds1 = rolePermissionMap.get(role.getId());
            if(!CollectionUtils.isEmpty(permissionIds1)){
                roleDetailDTO.setPermissionList(permissionIds1);
                Map<Integer, String> pm = permissionMap;
                roleDetailDTO.setPermissionNames(permissionIds1.stream().map(i -> pm.get(i)).collect(Collectors.toList()));
            }
            if(null != role.getEnterpriseId()){
                roleDetailDTO.setEnterpriseName(enterpriseMap.get(role.getEnterpriseId()));
            }
            if(null != role.getIndustryId()){
                roleDetailDTO.setIndustryName(industryMap.get(role.getIndustryId().intValue()));
            }
            roleDetailDTO.setTypeName(RoleTypeEnum.findRoleTypeEnum(roleDetailDTO.getType()).name);
            //设置场景
            List<String> names = sceneRoleDao.findSceneNames(role.getId());
            if(!CollectionUtils.isEmpty(names)) {
                roleDetailDTO.setSceneNames(Joiner.on(",").join(names));
            }
            roleDetailDTOS.add(roleDetailDTO);
        }
        roles.setRecords(roleDetailDTOS);
        return ResultJson.success(roles);
    }

    @PostMapping("/role/role-account-num")
    public Map<Integer, Long> roleAccountNum(@RequestBody List<Integer> roleIds){
        return roleAccountCount(roleIds);
    }

    /**
     * 角色人数统计
     * @param roleIds
     */
    private Map<Integer, Long> roleAccountCount(List<Integer> roleIds){
        Map<Integer, Long> roleCountMap = new HashMap<>();
        QueryWrapper<AdminAccountRole> adminAccountRoleQueryWrapper = new QueryWrapper<>();
        adminAccountRoleQueryWrapper.in("role_id", roleIds);
        List<AdminAccountRole> adminAccountRoles = adminAccountRoleService.list(adminAccountRoleQueryWrapper);
        if(!CollectionUtils.isEmpty(adminAccountRoles)){
            // 过滤掉删除的
            List<Integer> collect = adminAccountRoles.stream().map(i -> i.getAdminAccountId()).collect(Collectors.toList());
            QueryWrapper<AdminAccount> adminAccountQueryWrapper = new QueryWrapper<>();
            adminAccountQueryWrapper.select("id");
            adminAccountQueryWrapper.in("id", collect);
            adminAccountQueryWrapper.eq("is_deleted", false);
            List<AdminAccount> list = adminAccountService.list(adminAccountQueryWrapper);
            if(list.isEmpty()){
            }else{
                List<Integer> collect1 = list.stream().map(i -> i.getId()).collect(Collectors.toList());
                roleCountMap = adminAccountRoles.stream().filter(i -> collect1.contains(i.getAdminAccountId())).collect(Collectors.groupingBy(AdminAccountRole::getRoleId, Collectors.mapping(AdminAccountRole::getAdminAccountId, Collectors.counting())));
            }
        }
        QueryWrapper<AccountRole> accountRoleQueryWrapper = new QueryWrapper<>();
        accountRoleQueryWrapper.in("role_id", roleIds);
        List<AccountRole> accountRoles = accountRoleService.list(accountRoleQueryWrapper);
        if(!CollectionUtils.isEmpty(accountRoles)){
            // 排除删除的帐号
            List<Integer> collect = accountRoles.stream().map(i -> i.getAccountId()).collect(Collectors.toList());
            QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
            accountQueryWrapper.select("id");
            accountQueryWrapper.eq("is_deleted", false);
            accountQueryWrapper.in("id", collect);
            List<Account> list = accountService.list(accountQueryWrapper);
            if(list.isEmpty()){
                return roleCountMap;
            }
            List<Integer> collect1 = list.stream().map(i -> i.getId()).collect(Collectors.toList());
            Map<Integer, Long> roleCountMap1 = accountRoles.stream().filter(i -> collect1.contains(i.getAccountId())).collect(Collectors.groupingBy(AccountRole::getRoleId, Collectors.mapping(AccountRole::getAccountId, Collectors.counting())));
            if(!CollectionUtils.isEmpty(roleCountMap1)){
                for (Map.Entry<Integer, Long> en : roleCountMap1.entrySet()) {
                    if(null != roleCountMap.get(en.getKey())){
                        Long aLong = roleCountMap.get(en.getKey());
                        roleCountMap.put(en.getKey(), aLong + en.getValue());
                    }else{
                        roleCountMap.put(en.getKey(), en.getValue());
                    }
                }
            }
        }
        return roleCountMap;
    }


    /**
     * 获取角色详情 ，包含所关联的权限ids
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/role/detail", method = RequestMethod.GET)
    public ResultJson detail(
            @RequestHeader(value = "industryId", required = true) Short industryId,
            @RequestParam("id") Integer id,
            Account operateAccount, App app) {
        RoleDetailDTO roleDetail = roleService.getDetail(industryId, id);
        //获取当前登录操作账号的角色身份
        Role role = new Role();
        BeanUtils.copyProperties(roleDetail, role);
        if(null != operateAccount && null != operateAccount.getIndustryId()){
            RoleTypeEnum operateRoleType = roleService.getAccountRoleType(operateAccount.getId()).getRoleTypeEnum();
            //填充 该角色是否允许被当前操作账号 修改 / 删除
            Map<String, Boolean> canUpdateOrDeleteMap = canUpdateOrDelete(operateRoleType, role);
            roleDetail.setCanUpdate(canUpdateOrDeleteMap.get("canUpdate"));
            roleDetail.setCanDelete(canUpdateOrDeleteMap.get("canDelete"));
        }
        if(AppTypeEnum.SYSTEM.type == app.getAppType().intValue()){ // 后台应用

        }else{
            List<RoleDetailDTO> countList = roleService.getAccountCountByRoleId(Arrays.asList(role.getId()));
            Map<Integer, RoleDetailDTO> roleCountMap = countList.stream().collect(Collectors.toMap(RoleDetailDTO::getId, Function.identity()));
            //设置默认值 ，角色关联的账号计数为 0
            roleDetail.setCount(0);
            if (null != roleCountMap.get(role.getId())) {
                roleDetail.setCount(roleCountMap.get(role.getId()).getCount());
            }
            //获取该角色id的 挂钩 账号 ids
            List<Integer> accountIdList = accountService.getAccountIdListByRoleId(id);
            List<String> relatedAccountList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(accountIdList)) {
                AccountQuery accountQuery = new AccountQuery();
                List<String> selectColumnList = new ArrayList<>();
                selectColumnList.add("id");
                selectColumnList.add("login_name");
                accountQuery.setSelectColumnList(selectColumnList);
                //最多显示10个
                if (10 <= accountIdList.size()) {
                    accountIdList.subList(0, 10);
                }
                accountQuery.setIdList(accountIdList);
                List<Account> accountList = accountService.getAccountList(null, accountQuery);
                relatedAccountList = accountList.stream().map(Account::getLoginName).collect(Collectors.toList());
            }
            roleDetail.setRelatedAccountList(relatedAccountList);
        }
        //设置场景ids
        QueryWrapper<SceneRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleDetail.getId());
        List<SceneRole> sceneRoles = sceneRoleDao.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(sceneRoles)){
            roleDetail.setSceneIds(sceneRoles.stream().map(j -> j.getSceneId()).collect(Collectors.toList()));
        }
        return ResultJson.success(roleDetail);
    }


    /**
     * 角色 关联的账号信息查询
     *
     * @param page
     * @param roleId
     * @param operateAccount
     * @return
     */
    @RequestMapping(value = "/role/account-list", method = RequestMethod.GET)
    public ResultJson roleAccountList(Page page,
                                      @RequestHeader(value = "industryId", required = true) Short industryId,
                                      @RequestParam(value = "roleId", required = false) Integer roleId,
                                      Account operateAccount) {
        AccountQuery accountQuery = new AccountQuery();
        RoleTypeEnum operateRoleType = roleService.getAccountRoleType(operateAccount.getId()).getRoleTypeEnum();
        accountQuery.setOperateRoleType(operateRoleType);
        accountQuery.setRoleIdList(Arrays.asList(roleId));
//        accountQuery.setIndustryId(industryId);
        Page<AccountDTO> accountPageList = accountService.getPageList(page, accountQuery);
        return ResultJson.success(accountPageList);
    }


    /**
     * 角色 与企业/项目关联的树结构数据
     *
     * @param enterpriseIds
     * @param projectIds
     * @return
     */
    @GetMapping("/role/tree")
    public ResultJson roleTree(
            Account operateAccount,
            @RequestHeader(value = "industryId", required = true) Short industryId,
            @RequestParam(value = "enterpriseIds", required = false) List<Integer> enterpriseIds,
            @RequestParam(value = "projectIds", required = false) List<Integer> projectIds,
            @RequestParam(value = "needCommonIndRoles", required = false) Boolean needCommonIndRoles) {

        //默认为true
        if (null==needCommonIndRoles){
            needCommonIndRoles=true;
        }

        RoleQuery roleQuery = new RoleQuery();
        roleQuery.setEnterpriseIdList(enterpriseIds);
        roleQuery.setProjectIdList(projectIds);
        List<Role> roleList = getRoleList(operateAccount,industryId,roleQuery);
        //企业信息查找
        List<Enterprise> enterpriseList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(enterpriseIds)) {
            EnterpriseQuery enterpriseQuery = new EnterpriseQuery();
            enterpriseQuery.setIdList(enterpriseIds);
            enterpriseList = enterpriseService.list(enterpriseQuery, null);
        }
        List<Project> projectList = new ArrayList<>();
        //生成角色树
        List<RoleTreeDTO> result = treeMaker(industryId, enterpriseList, roleList, projectList, needCommonIndRoles);
        return ResultJson.success(roleList);
    }

    private List<Role> getRoleList(Account operateAccount,Short industryId,RoleQuery roleQuery){
        RoleTypeDTO accountRoleType = roleService.getAccountRoleType(operateAccount.getId());
        RoleTypeEnum operateRoleType = accountRoleType.getRoleTypeEnum();
        roleQuery.setIsContainGlobalRole(true);
        roleQuery.setIndustryIdList(Arrays.asList(industryId));
        roleQuery.setNeedCommonInitialized(true);
        //填充项目id （根据企业、项目反查出来涉及到的项目id）
        List<Integer> enterpriseIds = roleQuery.getEnterpriseIdList();
        List<Integer> projectIds = roleQuery.getProjectIdList();
        if(CollectionUtils.isEmpty(enterpriseIds)){
            enterpriseIds = new ArrayList<>();
        }
        fillProjectIds(industryId, enterpriseIds, projectIds, roleQuery);
        //根据操作人的角色身份权限过滤 部分角色数据（主要针对企管、项管）
        filterByOperateRoleType(accountRoleType, operateRoleType, roleQuery);
        //超管需要查询出对应业态的普通内置类型的角色
        if (RoleTypeEnum.SUPPER_MANAGER.getCode() == operateRoleType.getCode()) {
            List<Short> industryIdList = accountRoleType.getIndustryIdList();
            //普通角色、内置类型  ，例如学生、教工、家长、后勤、住户、员工
            List<Integer> commonInitializedRoles = roleService.getCommonInitializedRoles(industryIdList);
            if (!CollectionUtils.isEmpty(commonInitializedRoles)) {
                roleQuery.setCommonInitialized(commonInitializedRoles);
            }
        }
        // 角色树不展示企业超管
        roleQuery.setExcludeType(Arrays.asList(RoleTypeEnum.MANAGER.code));
        //查找出符合条件的 角色信息
        List<Role> roleList = roleService.getRoleList(null, roleQuery);
        // 补充查询企业内置角色
        RoleQuery roleQuery1 = new RoleQuery();
        roleQuery1.setEnterpriseIdList(enterpriseIds);
        roleQuery1.setGrade((short)1);
        roleQuery1.setIsInitialized(true);
        List<Role> roleList1 = roleService.getRoleList(null, roleQuery1);
        roleList.addAll(roleList1);
        if (CollectionUtils.isEmpty(roleList)) {
            return Collections.emptyList();
        }
        // 去重
        roleList = roleList.stream().collect(
                collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(Role::getId))), ArrayList::new)
        );
        return roleList;
    }

    /**
     * 企业通讯录迭代 替代/role/tree
     * @param account
     * @param industryId
     * @param roleQueryVO
     * @return
     */
    @PostMapping("/role/page/v2")
    public ResultJson pageV2(Account account,@RequestHeader(value = "industryId", required = true) Short industryId,
                           @RequestBody RoleQueryVO roleQueryVO){
        RoleQuery roleQuery = roleQueryVO.getRoleQuery();
        List<Role> roles = getRoleList(account,industryId,roleQuery);
        List<Role> result = new ArrayList<>();
        for (Role role : roles){
            if ((BusinessType.INDUSTRY.code == role.getGrade() && RoleTypeEnum.COMMON.getCode() == role.getType() && role.getIsInitialized())) {
                result.add(role);
            }
            if ((BusinessType.ENTERPRISE.code == role.getGrade() && roleQuery.getEnterpriseIdList().contains((role.getEnterpriseId())))
                    && RoleTypeEnum.MANAGER.getCode() != role.getType() && RoleTypeEnum.TOURIST.getCode() != role.getType()){
                result.add(role);
            }
        }
        if (null != roleQuery.getLikeName()){
            result = result.stream().filter(i -> i.getName().contains(roleQuery.getLikeName())).collect(Collectors.toList());
        }
        Page page = roleQueryVO.getPage();
        page.setRecords(PageUtil.page(page,result));
        return ResultJson.success(page);

    }


    /**
    * 升级脚本
    * 项目管理员角色升级
    */
    @GetMapping("/role/update-project-manager")
    public ResultJson updateProjectManager(){
        // 查询所有项目管理员角色 grade = 0 type = 2
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("name", "项目管理员");
        roleQueryWrapper.isNotNull("project_id");
        List<Role> list = roleService.list(roleQueryWrapper);
        log.info("更新的角色数量 {}", list.size());
        if(list.isEmpty()){
            return ResultJson.success();
        }
        List<Integer> projectIds = list.stream().map(i -> i.getProjectId()).distinct().collect(Collectors.toList());

        QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
        projectQueryWrapper.select("id", "name");
        projectQueryWrapper.in("id", projectIds);
        List<Project> list1 = projectService.list(projectQueryWrapper);
        Map<Integer, String> projectNameMap = list1.stream().collect(Collectors.toMap(Project::getId, Project::getName));

        // 逐条更新 升级脚本数据一般不会太多
        for (Role role : list) {
            UpdateWrapper<Role> roleUpdateWrapper = new UpdateWrapper<>();
            String s = projectNameMap.get(role.getProjectId());
            if(StringUtils.isEmpty(s)){
                log.info("角色 {} {} 的项目信息找不到", role.getId(), role.getName());
                continue;
            }
            if(role.getName().contains(s)){
                log.info("角色 {} {} 已经更新过了", role.getId(), role.getName());
                continue;
            }
            roleUpdateWrapper.set("name", s +"-"+ role.getName());
            roleUpdateWrapper.eq("id", role.getId());
            roleService.update(roleUpdateWrapper);
        }
        return ResultJson.success();
    }

    /**
     * 填充项目id （根据企业、项目反查出来涉及到的项目id）
     *
     * @param industryId
     * @param enterpriseIds
     * @param projectIds
     * @param roleQuery
     */
    public void fillProjectIds(Short industryId, List<Integer> enterpriseIds, List<Integer> projectIds, RoleQuery roleQuery) {
        if (!CollectionUtils.isEmpty(enterpriseIds)) {
            roleQuery.setEnterpriseIdList(enterpriseIds);
            //根据企业ids获取项目ids
            ProjectQuery projectQuery = new ProjectQuery();
            projectQuery.withEnterpriseIds(enterpriseIds);
//            projectQuery.withIndustryId(industryId);
            List<Project> projectList = projectService.list(projectQuery, null);
            List<Integer> proIds = projectList.stream().map(Project::getId).collect(Collectors.toList());
            roleQuery.setProjectIdList(proIds);
        } else if (!CollectionUtils.isEmpty(projectIds)) {
            ProjectQuery projectQuery = new ProjectQuery();
            projectQuery.withIdList(projectIds);
            // 项目改由运管平台创建后industryId变为运管平台的了
//            projectQuery.withIndustryId(industryId);
            List<Project> projectList = projectService.list(projectQuery, null);
            if (!CollectionUtils.isEmpty(projectList)) {
                List<Integer> eIds = projectList.stream().filter(e -> null != e.getEnterpriseId()).map(Project::getEnterpriseId).collect(Collectors.toList());
                roleQuery.setEnterpriseIdList(eIds);
                enterpriseIds.addAll(eIds);
            }
            roleQuery.setProjectIdList(projectIds);
        }
    }

    /**
     * 根据操作人的角色身份权限过滤 部分角色数据（主要针对企管、项管）
     *
     * @param accountRoleType
     * @param operateRoleType
     * @param roleQuery
     */
    public void filterByOperateRoleType(RoleTypeDTO accountRoleType, RoleTypeEnum operateRoleType, RoleQuery roleQuery) {
        //过滤 不能操作的角色
        // 2023-8-29 企管、普通员工不允许看到企业管理员角色
        if (RoleTypeEnum.ENT_MANAGER.getCode() == operateRoleType.getCode() || RoleTypeEnum.COMMON.getCode() == operateRoleType.getCode()) {
            //企业管理员， 不能看到企业管理员角色
            List<Integer> enterpriseIdList = accountRoleType.getEnterpriseIdList();
            RoleQuery excludeQuery = new RoleQuery();
            excludeQuery.setEnterpriseIdList(enterpriseIdList);
            excludeQuery.setType(RoleTypeEnum.MANAGER.getCode());
            excludeQuery.setGrade(BusinessType.ENTERPRISE.getCode());
            List<Role> entManagerRoleList = roleService.getRoleList(null, excludeQuery);
            List<Integer> entManagerIds = entManagerRoleList.stream().map(Role::getId).collect(Collectors.toList());
            roleQuery.setExcludeIdList(entManagerIds);
        }
        if (RoleTypeEnum.PRO_MANAGER.getCode() == operateRoleType.getCode()) {
            List<Integer> projectIdList = accountRoleType.getProjectIdList();
            List<Integer> proIds = roleQuery.getProjectIdList();
            List<Integer> proIdsCopy = new ArrayList<>(projectIdList);
            //项目id取交集，取决于项目管理员的ids
            List<Integer> manageProjectIdList = proIdsCopy.stream().filter(proIds::contains).collect(Collectors.toList());
            roleQuery.setProjectIdList(manageProjectIdList);
            ProjectQuery projectQuery = new ProjectQuery();
            projectQuery.withIdList(projectIdList);
            List<Project> projectList = projectService.list(projectQuery, null);
            List<Integer> entIds = projectList.stream().map(Project::getEnterpriseId).collect(Collectors.toList());
            //企业级别角色的ids
            RoleQuery excludeEntQuery = new RoleQuery();
            excludeEntQuery.setEnterpriseIdList(entIds);
            excludeEntQuery.setGrade(BusinessType.ENTERPRISE.getCode());
            List<Role> entManagerRoleList = roleService.getRoleList(null, excludeEntQuery);
            List<Integer> entManagerIds = entManagerRoleList.stream().map(Role::getId).collect(Collectors.toList());
            //项目管理员角色的ids
            RoleQuery excludeProQuery = new RoleQuery();
            excludeProQuery.setType(RoleTypeEnum.MANAGER.getCode());
            excludeProQuery.setGrade(BusinessType.PROJECT.getCode());
            List<Role> proManagerRoleList = roleService.getRoleList(null, excludeProQuery);
            List<Integer> proManagerIds = proManagerRoleList.stream().map(Role::getId).collect(Collectors.toList());
            //加入需要过滤的角色ids
            List<Integer> excludeIds = new ArrayList<>();
            excludeIds.addAll(entManagerIds);
            excludeIds.addAll(proManagerIds);
            roleQuery.setExcludeIdList(excludeIds);
        }
    }

    /**
     * 生成角色树，与企业、项目相关联
     *
     * @param enterpriseList
     * @param roleList
     * @param projectList
     * @return
     */
    private List<RoleTreeDTO> treeMaker(Short industryId, List<Enterprise> enterpriseList, List<Role> roleList, List<Project> projectList, Boolean needCommonIndRoles) {
        if (CollectionUtils.isEmpty(enterpriseList) || CollectionUtils.isEmpty(roleList)) {
            return Collections.emptyList();
        }
        List<RoleTreeDTO> result = new ArrayList<>(enterpriseList.size());
        for (Enterprise enterprise : enterpriseList) {
            RoleTreeDTO dto = new RoleTreeDTO();
            dto.setId(enterprise.getId());
            dto.setEnterpriseId(enterprise.getId());
            dto.setName(enterprise.getName());
            dto.setKeywords("ent-" + enterprise.getId() + "-" + enterprise.getName());
            dto.setChildren(rolePropertyMaker(industryId, enterprise.getId(), roleList, projectList, needCommonIndRoles));
            result.add(dto);
        }
        return result;
    }

    /**
     * 角色子树递归数据生成
     *
     * @param industryId
     * @param enterpriseId
     * @param roles
     * @param projectList
     * @return
     */
    private List<RoleTreeDTO> rolePropertyMaker(Short industryId, Integer enterpriseId, List<Role> roles, List<Project> projectList,Boolean needCommonIndRoles) {
        List<RoleTreeDTO> result = new ArrayList<>(projectList.size() + 1);

        Enterprise enterprise = enterpriseService.findById(enterpriseId);

        Map<Integer, String> proNameMap=new HashMap<>();
        if(!CollectionUtils.isEmpty(projectList)){
            proNameMap=projectList.stream().collect(Collectors.toMap(Project::getId, Project::getName));
        }
        //项目级别角色集合
        Map<Project, List<Role>> projectRoleInProjects = new HashMap<>();
        for (Project project : projectList) {
            projectRoleInProjects.put(project, null);
        }
        for (Map.Entry<Project, List<Role>> e : projectRoleInProjects.entrySet()) {
            List<Role> list = new ArrayList<>();
            for (Role role : roles) {
                if (BusinessType.PROJECT.code == role.getGrade() && enterpriseId.equals(role.getEnterpriseId()) && role.getProjectId().equals(e.getKey().getId())) {
                    list.add(role);
                }
            }
            e.setValue(list);
        }
        //业态级别角色list
        if (needCommonIndRoles){
            List<Role> industryInitializedRoles = new ArrayList<>();
            for (Role role : roles) {
                if ((BusinessType.INDUSTRY.code == role.getGrade() && RoleTypeEnum.COMMON.getCode() == role.getType() && role.getIsInitialized())) {
                    industryInitializedRoles.add(role);
                }
            }
            industryRoleSetter(industryInitializedRoles, industryId, result);

        }
        //企业级别角色list
        enterpriseRoleSetter(roles, enterprise, result);

        boolean hasProjects = false;
        for (Map.Entry<Project, List<Role>> entry : projectRoleInProjects.entrySet()) {
            if (null != entry.getValue() && !entry.getValue().isEmpty()) {
                hasProjects = true;
            }
        }
        //项目角色部分
        if (hasProjects) {
            projectRoleSetter(enterpriseId, projectRoleInProjects, proNameMap, result);
        }

        return result;
    }

    private void industryRoleSetter(List<Role> industryInitializedRoles, Short industryId, List<RoleTreeDTO> result){
        //业态角色部分
        RoleTreeDTO industryInitializedGlobal = new RoleTreeDTO();
        industryInitializedGlobal.setId(0);
        industryInitializedGlobal.setName("平台角色");
        industryInitializedGlobal.setKeywords("industry-" + industryId + "-" + "平台角色");
        industryInitializedGlobal.setChildren(Collections.EMPTY_LIST);
        if (!CollectionUtils.isEmpty(industryInitializedRoles)) {
            industryInitializedGlobal.setChildren(industryInitializedRoles.stream().map(r -> {
                RoleBlockDTO roleBlockDTO = roleToDTO(r, null);
                roleBlockDTO.setKeywords("role-" + r.getId() + "-" + r.getName());
                return roleBlockDTO;
            }).collect(Collectors.toList()));
            result.add(industryInitializedGlobal);
        }
    }

    private void enterpriseRoleSetter(List<Role> roles, Enterprise enterprise, List<RoleTreeDTO> result){
        List<Role> globalRoleInProjects = new ArrayList<>();
        for (Role role : roles) {
            if (null != role.getEnterpriseId()) {
                if ((BusinessType.ENTERPRISE.code == role.getGrade() && enterprise.getId().equals(role.getEnterpriseId()))) {
                    globalRoleInProjects.add(role);
                }
            }
        }
        RoleTreeDTO entGlobal = new RoleTreeDTO();
        entGlobal.setId(-1);
        entGlobal.setName("企业角色");
        entGlobal.setEnterpriseId(enterprise.getId());
        entGlobal.setKeywords("common-" + enterprise.getId() + "-" + "企业角色");
        entGlobal.setChildren(Collections.EMPTY_LIST);
        //企业（全局）角色部分
        if (!CollectionUtils.isEmpty(globalRoleInProjects)) {
            entGlobal.setChildren(globalRoleInProjects.stream().map(r -> {
                RoleBlockDTO roleBlockDTO = roleToDTO(r, enterprise);
                roleBlockDTO.setKeywords("role-" + r.getId() + "-" + r.getName()+"-"+enterprise.getName());
                return roleBlockDTO;
            }).collect(Collectors.toList()));
            result.add(entGlobal);
        }
    }

    private void projectRoleSetter(Integer enterpriseId, Map<Project, List<Role>> projectRoleInProjects, Map<Integer, String> proNameMap, List<RoleTreeDTO> result){
        for (Map.Entry<Project, List<Role>> entry : projectRoleInProjects.entrySet()) {
            RoleTreeDTO projectBlock = new RoleTreeDTO();
            projectBlock.setId(entry.getKey().getId());
            projectBlock.setName(entry.getKey().getName());
            projectBlock.setKeywords("pro-" + entry.getKey().getId() + "-" + entry.getKey().getName());
            projectBlock.setEnterpriseId(enterpriseId);
            projectBlock.setProjectId(entry.getKey().getId());
            projectBlock.setChildren(Collections.EMPTY_LIST);
            if (null == entry.getValue() || entry.getValue().isEmpty()) {
                continue;
            }
            Map<Integer, String> finalProNameMap = proNameMap;
            projectBlock.setChildren(entry.getValue().stream().map(r -> {
                RoleBlockDTO dto = roleToDTO(r, null);
                Integer projectId = r.getProjectId();
                String proName = finalProNameMap.get(projectId);
                dto.setKeywords("role-" + r.getId() + "-" + r.getName()+"-"+proName);
                dto.setEnterpriseId(enterpriseId);
                dto.setProjectId(r.getProjectId());
                return dto;
            }).collect(Collectors.toList()));
            result.add(projectBlock);
        }
    }

    private RoleBlockDTO roleToDTO(Role r, Enterprise enterprise){
        RoleBlockDTO dto = new RoleBlockDTO();
        dto.setId(r.getId());
        dto.setRoleId(r.getId());
        dto.setName(r.getName());
        dto.setCode(r.getCode());
        dto.setEnterpriseId(null == enterprise ? null:enterprise.getId());
        dto.setType(r.getType());
        dto.setChildren(Collections.EMPTY_LIST);
        return dto;
    }


    /**
     * 传入组织id，转化出相关联的项目id
     * 注意： 如果是企业的组织id，就需要找到该企业下的所有项目的id
     *
     * @param organizationIds
     * @return
     */
    public RoleQuery covertOrProIdEntIds(List<Integer> organizationIds) {
        RoleQuery roleQuery = new RoleQuery();
        OrganizationQuery organizationQuery = new OrganizationQuery();
        organizationQuery.withIds(organizationIds);
        List<Organization> orgList = organizationService.list(organizationQuery);
        List<Organization> entOrgList = new ArrayList<>();
        List<Organization> proOrgList = new ArrayList<>();
        for (Organization organization : orgList) {
            Integer type = organization.getType();
            //如果是企业级组织
            if (OrganizationTypeEnum.ENTERPRISE.id.intValue() == type) {
                entOrgList.add(organization);
            }
            //如果是项目级组织
            if (OrganizationTypeEnum.PROJECT.id.intValue() == type) {
                proOrgList.add(organization);
            }
        }
        List<Integer> proIdResultList = new ArrayList<>();
        List<Integer> entIdResultList = new ArrayList<>();
        //根据企业的组织id 转换出所有项目id
        if (!CollectionUtils.isEmpty(entOrgList)) {
            List<Integer> entIdList = entOrgList.stream().map(e -> e.getEnterpriseId()).collect(Collectors.toList());
            entIdResultList.addAll(entIdList);
            ProjectQuery projectQuery = new ProjectQuery();
            projectQuery.withEnterpriseIds(entIdList);
            List<Project> proList = projectService.list(projectQuery, null);
            if (!CollectionUtils.isEmpty(proList)) {
                List<Integer> proIdList = proList.stream().map(e -> e.getId()).collect(Collectors.toList());
                proIdResultList.addAll(proIdList);
            }
        }
        //根据项目的组织id 转换出所有项目id
        if (!CollectionUtils.isEmpty(proOrgList)) {
            List<Integer> orgIdList = proOrgList.stream().map(e -> e.getId()).collect(Collectors.toList());
            ProjectQuery projectQuery = new ProjectQuery();
            projectQuery.withOrganizationIds(orgIdList);
            List<Project> proList = projectService.list(projectQuery, null);
            if (!CollectionUtils.isEmpty(proList)) {
                List<Integer> proIdList = proList.stream().map(e -> e.getId()).collect(Collectors.toList());
                proIdResultList.addAll(proIdList);
            }
        }
        //去重后的项目id，用于做查询条件
        HashSet<Integer> proIdsSet = new HashSet<>(proIdResultList);
        proIdResultList.clear();
        proIdResultList.addAll(proIdsSet);
        roleQuery.setOrProjectIdList(proIdResultList);
        HashSet<Integer> entIdsSet = new HashSet<>(entIdResultList);
        entIdResultList.clear();
        entIdResultList.addAll(entIdsSet);
        roleQuery.setOrEnterpriseIdList(entIdResultList);
        return roleQuery;
    }


    /**
     * 完善角色查询列表的list,填充信息
     *
     * @param roleList
     * @param roleOrgStructureData
     * @param operateRoleType
     * @return
     */
    public List<RoleDetailDTO> fillRoleDetailList(List<Role> roleList, RoleOrgStructureDTO roleOrgStructureData, RoleTypeEnum operateRoleType) {
        Map<Integer, Integer> enterpriseOrganizationMap = new HashMap<>();
        Map<Integer, Integer> projectOrganizationMap = new HashMap<>();
        Map<Integer, String> organizationNameMap = new HashMap<>();
        if (null != roleOrgStructureData) {
            enterpriseOrganizationMap = roleOrgStructureData.getEnterpriseOrganizationMap();
            projectOrganizationMap = roleOrgStructureData.getProjectOrganizationMap();
            organizationNameMap = roleOrgStructureData.getOrganizationNameMap();
        }
        List<RoleDetailDTO> countList = roleService.getAccountCountByRoleId(roleList.stream().map(i -> i.getId()).collect(Collectors.toList()));
        Map<Integer, RoleDetailDTO> roleCountMap = countList.stream().collect(Collectors.toMap(RoleDetailDTO::getId, Function.identity()));
        List<RoleDetailDTO> resultList = new ArrayList<>();
        //功能权限校验 （是否能修改、删除）
        Map<Integer, Boolean> updateCheckBatchMap = roleService.updateRoleCheckBatch(operateRoleType, roleList);
        Map<Integer, Boolean> deleteCheckBatchMap = roleService.deleteRoleCheckBatch(operateRoleType, roleList);
        for (Role role : roleList) {
            Integer roleId = role.getId();
            RoleDetailDTO roleDetailDTO = new RoleDetailDTO();
            BeanUtils.copyProperties(role, roleDetailDTO);
            //设置默认值 ，角色关联的账号计数为 0
            roleDetailDTO.setCount(0);
            if (null != roleCountMap.get(role.getId())) {
                roleDetailDTO.setCount(roleCountMap.get(role.getId()).getCount());
            }
            String orgStructureName = null;
            Integer orgId = null;
            if (null != role.getProjectId()) {
                orgId = projectOrganizationMap.get(role.getProjectId());
            } else {
                orgId = enterpriseOrganizationMap.get(role.getEnterpriseId());
            }
            if (null != orgId) {
                orgStructureName = organizationNameMap.get(orgId);
            }
            //填充  该角色的组织架构全名
            roleDetailDTO.setOrgStructureName(orgStructureName);
            //填充 角色类型名称
            if (null != roleDetailDTO.getType()) {
                RoleTypeEnum roleTypeEnum = RoleTypeEnum.findRoleTypeEnum(roleDetailDTO.getType());
                roleDetailDTO.setTypeName(roleTypeEnum.getName());
            }
            //填充角色是否内置名称
            if (null != roleDetailDTO.getIsInitialized()) {
                if (roleDetailDTO.getIsInitialized()) {
                    roleDetailDTO.setIsInitializedName("内置角色");
                } else {
                    roleDetailDTO.setIsInitializedName("自定义角色");
                }
            }
            //填充 该角色是否允许被当前操作账号 修改 / 删除
            roleDetailDTO.setCanUpdate(updateCheckBatchMap.get(roleId));
            roleDetailDTO.setCanDelete(deleteCheckBatchMap.get(roleId));
            resultList.add(roleDetailDTO);
        }
        return resultList;

    }


    /**
     * 单个校验 该角色是否允许被当前操作账号 修改 / 删除
     *
     * @param operateRoleType
     * @param role
     * @return
     */
    public Map<String, Boolean> canUpdateOrDelete(RoleTypeEnum operateRoleType, Role role) {
        Map<String, Boolean> map = new HashMap<>(2);
        Boolean checkUpdateResult = roleService.updateRoleCheck(operateRoleType, role);
        map.put("canUpdate", checkUpdateResult);
        Boolean checkDeleteResult = roleService.deleteRoleCheck(operateRoleType, role);
        map.put("canDelete", checkDeleteResult);
        return map;
    }

}
